<template>
  <a-drawer :title="titleMap" :width="600" :visible.sync="visible"
            :body-style="{ 'padding-top': '0px', paddingBottom: '80px' }" @close="close">
    <a-form :form="form" :label-col="{ span: 5 }" :wrapper-col="{ span: 17 }" layout="horizontal">
      <a-form-item :label="$t( 'u111')">
        <br>
        <a-input v-decorator="[
          'YtRoleName',
          { rules: [{ required: true, message: $t('u113') }] },
        ]" :placeholder="$t('u113')" style="margin-left: -94px;"/>
      </a-form-item>
      <a-form-item :label="$t( 'u112')">
        <br>
        <a-input v-decorator="[
          'YtRoleNameEn',
          { rules: [{ required: true, message: $t( 'u114') }] },
        ]" :placeholder="$t( 'u114')" style="margin-left: -94px;"/>
      </a-form-item>
      <div style="position: relative;margin-left: 22px;">{{ $t('user.verification-code.required1115661100') }}:
        <div
            style="color: red;margin-top: -10px;display: inline-block;position: absolute;top: 9px;left: -10px;z-index: 99;">
          *
        </div>
      </div>
      <a-form-item>
        <div v-for="(item, index) in inputList" :key="index" style="margin-left: 30px;">
          <a-row>
            <a-col :span="24">
              <!--     功能下拉       -->
              <a-select :placeholder="$t('user.verification-code.required1115661101911')"
                        @change="findAuthorityDrownDrop(item.YtAdminRoleFunction,index)"
                        v-model="item.YtAdminRoleFunction"
                        style="width: 158px;">
                <a-select-option v-for="item in funList" :value="item.value" :key="item.value">
                  {{ item.label }}
                </a-select-option>
              </a-select>
              <!--     权限下拉       -->
              <a-select :placeholder="$t('user.verification-code.required1115661101911')"
                        style="width: 148px;" mode="multiple"
                        v-model="item.YtRoleAuthority"
                        
                        >
                <a-select-option v-for="item in authorityLists" :value="item.value" :key="item.value">
                  {{ item.label }}
                </a-select-option>
              </a-select>
              <a-button type="link" @click="deleteInput(item)">{{ $t('menu.exception.trigger') }}</a-button>
            </a-col>
          </a-row>
        </div>
        <a-button style="float: left; margin-left: 30px" @click="addInput">{{
            $t('user.verification-code.required1115661106')
          }}
        </a-button>
      </a-form-item>
    </a-form>
    <!-- 下方按钮 -->
    <div
        class="absolute right-0 bottom-0 w-full border-t border-[#e9e9e9] px-4 py-[10px] bg-white text-left z-1 flex justify-center">
      <a-button :style="{ marginRight: '20px' }" class="w-[200px]" @click="close">{{
          $t('user.email.required11')
        }}
      </a-button>
      <a-button :loading="loading" class="w-[200px]" type="primary" @click.native.prevent="submit()">
        <span v-if="!loading">{{ $t('app.setting.weakmode') }}</span>
        <span v-else>{{ $t('user.verification-code.required1115661107') }}...</span>
      </a-button>
    </div>
  </a-drawer>
</template>

<script>
import {authorityDropDown, authorityDrownDrop, authorityList, authorityQuery} from "@/api/index";
import {userRolesCreate} from "@/api/indexJson";

export default {
  data() {
    return {
      sourceData: {},
      form: this.$form.createForm(this),
      funList: [],
      authorityLists: [],
      visible: false,
      loading: false,
      titleMap: '',
      // titleMap: ["创建角色", "编辑角色"],
      mode: 0,
      roleId: 0,
      YtRoleName: "",
      YtRoleNameEn: '',
      inputList: [],
      // 当前的权限提交data
      powerSubmitData: [],
    };
  },
  methods: {
    authorityList,
    // 转换权限值(递归操作),v代表当前子childen，i代表当前子childen的索引
    setPowerState(v, i) {
      let arr = [];
      if (Array.isArray(v)) {
        arr = v.map((v, j) => {
          let data = {};
          if (Array.isArray(v.children)) {
            const childrenData = this.setPowerState(v.children, j);
            if (childrenData) {
              data = {children: childrenData};
            }
          }
          return {
            ...data,
            label: v.YtAuthorityName ?? "",
            value: v.Id ?? "",
            roleFunction: v.YtAuthorityFunction ?? "",
            //当前的父索引
            fatchIndex: i,
            //当前的索引
            currentIndex: j,
            // 循环递归，直到没用子项为止
            children: v.children,
          };
        });
      }
      return arr;
    },
    // 遍历所有值
    forPowerState(data) {
      const powerData = Array.isArray(data) ? data : [];
      return powerData.map((v, i) => {
        // 获取角色权限
        if (Array.isArray(v.children)) {
          const data = this.setPowerState(v.children, i);
          // 有值时返回
          if (data) {
            v.children = data;
          }
        }
        return v;
      });
    },
    // 去除多余值以及重复
    deletePower() {
      // 去除多余值
      let {inputList, powerSubmitData} = this;
      console.log('inp', inputList);
      console.log('pow', powerSubmitData);
      powerSubmitData = powerSubmitData.filter((v) => {
        const roleId = v.roleId;

        return inputList.some((item) => {
          if (item.value.length == 3) {
            return item.value[item.value.length - 3] == roleId
          } else if (item.value.length == 2) {
            return item.value[item.value.length - 2] == roleId
          } else {
            return item.value[item.value.length - 1] == roleId
          }
        })

      });
      console.log(powerSubmitData);
      // 临时操作数据
      let data = [];
      // 去重，重复选择后的数据去重
      powerSubmitData.forEach((item) => {
        if (data.findIndex((v) => v.roleId === item.roleId) < 0) {
          data.push(item);
        }
      });
      console.log(data);
      this.powerSubmitData = data;
    },
    /**
     * 查询功能的权限
     * @param e 根据功能ID查权限
     * @returns {Promise<void>}
     */
    async findAuthorityDrownDrop(e,index) {
      this.authorityLists= []
      if(this.inputList[index]){
      this.inputList[index].YtRoleAuthority = undefined
      }
      const {data: authorityLists} = await authorityDrownDrop({YtAuthorityFunction: e})
      this.authorityLists = authorityLists
    },

    /**
     *
     * @param {*} type 0 新增
     * @param {*} data 1 修改
     */
    async open(mode = 0, data = {}) {
      this.titleMap = this.$t('user.verification-code.required111566110577150')
      let {YtRoleFunctionIdAuthority} = data;
      this.sourceData = JSON.parse(JSON.stringify(data));
      this.inputList = [];
      this.powerSubmitData = [];
      this.addInput();
      const res = await authorityQuery();
      this.mode = mode;

      // 获取所有的功能
      const {data: dataList} = await authorityDropDown();
      this.funList = dataList;

      this.visible = true;
      if (mode == 1) {
        this.titleMap = this.$t('user.verification-code.required111566110577151')
        // 属于宏任务，在所有的异步任务执行完成后执行，相当于使用setTimeout(()=>{},0)
        this.roleId = data.YtId;
        await this.$nextTick();
        this.form.setFieldsValue({
          YtRoleName: data.YtRoleName,
          YtRoleNameEn: data.YtRoleNameEn,
        });
        let inputList = [];
        for (var i=0; i<YtRoleFunctionIdAuthority.length; i++){
          if(YtRoleFunctionIdAuthority[i].AuthorityId){
            this.findAuthorityDrownDrop(YtRoleFunctionIdAuthority[i].Function)
          }
          let arr = []
          if(YtRoleFunctionIdAuthority[i].AuthorityId){
            YtRoleFunctionIdAuthority[i].AuthorityId.split(',').forEach(item =>{
              arr.push(parseInt(item))
            })
          }
          
          inputList.push({
            YtAdminRoleFunction: YtRoleFunctionIdAuthority[i].Function,
            // YtRoleAuthority:YtRoleFunctionIdAuthority[i].AuthorityId? parseInt(YtRoleFunctionIdAuthority[i].AuthorityId): undefined,
            YtRoleAuthority:arr,
            YtId:data.YtId,
          })
        }
        this.inputList = inputList
        console.log("Inputs:",inputList)
        console.log(this.authorityLists);

        // // 不是数组或者为空数组
        // if (
        //     !Array.isArray(YtRoleFunctionIdAuthority) ||
        //     !YtRoleFunctionIdAuthority.length
        // ) {
        //   inputList.push({
        //     value: [],
        //   });
        // } else {
        //   inputList = YtRoleFunctionIdAuthority.map((v) => {
        //     const value = [];
        //     if (v["Function"]) {
        //       value[0] = v["Function"];
        //     }
        //     if (parseInt(v["AuthorityId"])) {
        //       value[1] = parseInt(v["AuthorityId"]);
        //     }
        //     value[2] = v["Id"]
        //     return {
        //       value
        //     };
        //   });
        // }
        // this.inputList = inputList;
        // console.log(this.inputList);
        // this.powerSubmitData = inputList.map((v) => {
        //   return {
        //     // 父级
        //     roleFunction: v.value[0],
        //     // 权限
        //     roleId: v.value[1] ? v.value[1] : v.value[0],
        //     Id: v.value[2]
        //   };
        // });
        // console.log(this.powerSubmitData);
        // // 对角色权限强判断
        // YtRoleFunctionIds = Array.isArray(YtRoleFunctionIds)?YtRoleFunctionIds:[];
        // YtRoleFunctionName = Array.isArray(YtRoleFunctionName)?YtRoleFunctionName:[];
        // // 初始化input渲染循环数
        // this.inputList = new Array(YtRoleFunctionIds.length);
        // // 找权限id
        // const ids = YtRoleFunctionIds.map((v,i)=>{
        //   // v就是当前角色id 通过角色id匹配table列的id，找到其索引
        //   const index = funList.findIndex(item=>item.value===v);
        //   // 找到索引后，根据name获取权限id，最后将其进行拼接
        //   const children = Array.isArray(funList[index].children)?funList[index].children:[];
        //   // 存在chilren权限列时，再遍历
        //   if(funList[index].children.length){
        //     // 通过name去找权限id
        //     const childrenId = funList[index].children.find(item=>item.)
        //   }else{
        //     // 不存在，直接返回当前的角色id
        //   }
        // })
        // await this.$nextTick()
        // this.roleId = data.YtId;
        // this.YtRoleName = data.YtRoleName;
        // if (data.YtRoleFunctionIds.length > 0) {
        //   for (var i = 0; i < data.YtRoleFunctionIds.length; i++) {
        //     // 创建备注列表初始化
        //     this.inputList.unshift({
        //       Id:i,
        //       valueId: data.YtRoleFunctionIds[i],
        //     });
        //     console.log(this.inputList);
        //   }
        // }
      }
      setTimeout(()=>{
        this.authorityLists = []
      },500)
      console.log(this.authorityLists);
    },
   
    submit() {
      const {
        form: {validateFields},
      } = this;
      this.loading = true;
      const {YtRoleName, roleId, YtRoleNameEn} = this;
      validateFields(
          ["YtRoleName", "roleFunction", 'YtRoleNameEn'],
          {force: true},
          async (err, values) => {
            if (!err) {
              console.log(values);
              console.log(this.inputList);
              // values.roleFunction = values.roleFunction.join(',')
              try {
                // 先获取所有的权限id数组，再使用join转换数组，以逗号隔开，返回字符串
                //功能
                // let role = this.powerSubmitData
                //   .map((v) => v.roleFunction)
                //   .join(",");
                //权限
                // let roleFunction = this.powerSubmitData
                //   .map((v) => v.roleId)
                //   .join(",");
                console.log(values);
                
                const arr = [];
                this.inputList.forEach((item) => {
                  arr.push({
                    // YtId: item.YtId,
                    // 父级
                    YtAdminRoleFunction: item.YtAdminRoleFunction,
                    // 权限
                    YtRoleAuthority:item.YtRoleAuthority? item.YtRoleAuthority.join(','): undefined,
                  });
                });
                if (arr.length == 0) {
                  this.$message.error('请选择关联功能')
                  return
                }
                console.log(arr);
                this.mode == 0
                    ? // ? await createRole({ ...values })
                    // ? await userRolesCreate({YtRoleName:values.YtRoleName, YtAdminRoleFunction:roleFunction,YtAuthorityId:role })
                    await userRolesCreate({
                      YtRoleName: values.YtRoleName,
                      YtRoleNameEn: values.YtRoleNameEn,
                      RoleAuthority: arr,
                    })
                    : await userRolesCreate({
                      YtRoleName: values.YtRoleName,
                      YtRoleNameEn: values.YtRoleNameEn,
                      // Id: this.roleId,
                      YtId: this.inputList[0].YtId,
                      RoleAuthority: arr,
                    });
                this.$emit("succeed");
                this.$message.success(this.$t('user.verification-code.required111566110577308'))
                this.close();
              } catch (error) {
                this.$message.error(error);
                console.log(error);
              } finally {
                this.loading = false;
              }
            } else {
              setTimeout(() => {
                this.loading = false;
              }, 600);
            }
          }
      );
    },
    close() {
      this.inputList = [];
      this.funList = []
      this.visible = false;
      this.form.resetFields();
    },
    onChange(value, index) {
      this.inputList[index].value = [value[value.length - 1]];
    },
    // 添加
    addInput() {
      // 新增一个新的数据初始化
      this.inputList.push({YtAdminRoleFunction: undefined, YtRoleAuthority:undefined});
    },
    //删除
    async deleteInput(item) {
      // 删除备注
      try {
        console.log("delete:", item)
        var {YtRoleFunctionIdAuthority} = this.sourceData;
        console.log("this!~:", YtRoleFunctionIdAuthority)
        console.log("==========>", this.sourceData)
        this.inputList = []
        var YtRoleFunctionIdAuthorityLists = []

        for (var i=0; i<YtRoleFunctionIdAuthority.length; i++){
          if (item.YtId === this.sourceData.YtId && item.YtAdminRoleFunction === YtRoleFunctionIdAuthority[i].Function){
            continue
          }else{
            YtRoleFunctionIdAuthorityLists.push(YtRoleFunctionIdAuthority[i])
            if(YtRoleFunctionIdAuthority[i].AuthorityId){
              this.findAuthorityDrownDrop(YtRoleFunctionIdAuthority[i].Function)
            }
            let arr = []
            if(YtRoleFunctionIdAuthority[i].AuthorityId){
              YtRoleFunctionIdAuthority[i].AuthorityId.split(',').forEach(item =>{
                arr.push(parseInt(item))
              })
            }
            this.inputList.push({
              YtAdminRoleFunction: YtRoleFunctionIdAuthority[i].Function,
              YtRoleAuthority:arr,
              YtId:this.sourceData.YtId,
            })
          }
        }
        this.sourceData["YtRoleFunctionIdAuthority"] = YtRoleFunctionIdAuthorityLists;

      } catch (error) {
        console.log("error:", error);
        this.$message.error(error);
      }
    },
  },
};
</script>
<style lang="less" scoped>
.shadow {
  box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.2);
}

.ant-form-item-label {
  display: inline-block;
  overflow: visible !important;
  line-height: 39.9999px;
  white-space: nowrap;
  text-align: right;
  vertical-align: middle;
}
</style>